package com.heima.homeservicemanagementsystem.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.homeservicemanagementsystem.entity.SysPermission;
import com.heima.homeservicemanagementsystem.module.PageParams;
import com.heima.homeservicemanagementsystem.module.Result;
import com.heima.homeservicemanagementsystem.service.SysPermissionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;


/**
 * 权限表;(sys_permission)表控制层
 *
 * @author : http://www.chiner.pro
 * @date : 2024-11-25
 */
@Slf4j
@Tag(name = "权限表或者菜单接口")
@RestController
@SaCheckRole
@RequestMapping("/sysPermission")
public class SysPermissionController {

    @Resource
    private SysPermissionService sysPermissionService;

    @Operation(summary = "分页查询菜单显示也可以查询父菜单")
    @PostMapping("/page")
    public Result<Page<SysPermission>> paginQuery(@RequestBody PageParams<SysPermission> pageParams) {
        //查询参数
        SysPermission params = pageParams.getParams();
        LambdaQueryWrapper<SysPermission> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SysPermission::getType, params.getType());
        lqw.like(params.getName() != null, SysPermission::getName, params.getName());
//        lqw.eq(params.getEnglishName() != null, SysPermission::getEnglishName, params.getEnglishName());
        lqw.orderByAsc(SysPermission::getSort);
        Page<SysPermission> page = sysPermissionService.page(pageParams.getPage(), lqw);
        if (params.isTree()) {
            //     4.处理结果i
            sysPermissionService.tree(page.getRecords());

        }

        return Result.success(page);
    }

    @Operation(summary = "查询菜单显示也可以查询父菜单")
    @PostMapping("/getadd")
    public Result<List<SysPermission>> Query(@RequestBody SysPermission pageParams) {
        //查询参数
//        SysPermission params = pageParams.getParams();
        LambdaQueryWrapper<SysPermission> lqw = new LambdaQueryWrapper<>();
        lqw.eq(pageParams.getType() != null, SysPermission::getType, pageParams.getType());
        lqw.like(pageParams.getName() != null, SysPermission::getName, pageParams.getName());
//        lqw.eq(pageParams.getEnglishName() != null, SysPermission::getEnglishName, pageParams.getEnglishName());
        lqw.orderByAsc(SysPermission::getSort);
        List<SysPermission> list = sysPermissionService.list(lqw);
        log.info("传递的参数{}", pageParams);
        log.info("结果{}", list);
        if (pageParams.isTree()) {
//            //     4.处理结果i
            sysPermissionService.tree(list);
//
        }
        log.info("查询之后的数据：{}", list);
        return Result.success(list);
    }

    @Operation(summary = "获取所有的权限信息")
    @GetMapping("/getsyspermission")
    public Result getSysPermission() {
        List<SysPermission> list = sysPermissionService.list();
        List<SysPermission> collect = list.stream().filter(sysPermission -> sysPermission.getType() == 2).collect(Collectors.toList());
        List<Object> collect1 = collect.stream().map(sysPermission -> {
            JSONObject entries = new JSONObject();
            entries.putOnce("id", sysPermission.getId());
            entries.putOnce("label", sysPermission.getName());
            entries.putOnce("value", sysPermission.getId());

            return entries;
        }).collect(Collectors.toList());
        log.info("获取权限信息:{}", collect1);


        return Result.success(collect1);
    }

    /**
     * 新增数据
     *
     * @param sysPermission 实例对象
     * @return 实例对象
     */
    @Operation(summary = "新增菜单/权限数据")
    @PostMapping("/insert")
    public Result<Boolean> insert(@RequestBody SysPermission sysPermission) {
        QueryWrapper<SysPermission> Wrapper = new QueryWrapper<>();
        Wrapper.eq("name", sysPermission.getName());
        boolean exists = sysPermissionService.getOne(Wrapper) != null;

        if (exists) {
            return Result.error("菜单或权限已经被注册~");
        } else {
            if (sysPermissionService.save(sysPermission)) {
//                SaSession saSession = StpUtil.getSessionByLoginId(StpUtil.getLoginId());
//
//// 移除会话中存储的菜单数据
//                saSession.delete("menu");
                return Result.success();
            } else {
                return Result.error("菜单或权限名称已经被注册~");
            }

        }


    }

    /**
     * 更新数据
     *
     * @param sysPermission 实例对象
     * @return 实例对象
     */
    @Operation(summary = "更新权限")
    @PutMapping("update")
    public Result<Boolean> update(@RequestBody SysPermission sysPermission) {
        if (sysPermissionService.updateById(sysPermission)) {

            return Result.success();
        }
        return Result.error();
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Operation(summary = "通过主键删除数据",
            parameters = {
                    @Parameter(name = "id", description = "主键", required = true, in = ParameterIn.PATH)
            })
    @GetMapping("/delete/{id}")
    public Result<Boolean> deleteById(@PathVariable String id) {

        if (sysPermissionService.removeById(id)) {
            return Result.success();
        }
        return Result.error();
    }
    @Operation(summary = "多id删除数据")
    @PostMapping("/delete")
    public Result<Boolean> deleteByIds(@RequestBody List<String> id) {
//        sysRoleService.removeByIds()
//        log.info("前端信息：{}", id);

        if (sysPermissionService.removeByIds(id)) {
//            sysPermissionService.removeMeprebyId(id);
            return Result.success();
        }
        return Result.error();
    }


}